package com.kexilo.core.common.config;

import com.kexilo.core.common.utils.Threads;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 *
 * @author Kexilo
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig {
    
    private static final Logger log = LoggerFactory.getLogger(ThreadPoolConfig.class);
    
    @Value("${spring.task.execution.pool.core-size:10}")
    private int corePoolSize;
    
    @Value("${spring.task.execution.pool.max-size:50}")
    private int maxPoolSize;
    
    @Value("${spring.task.execution.pool.queue-capacity:1000}")
    private int queueCapacity;
    
    @Value("${spring.task.execution.pool.keep-alive:60}")
    private int keepAliveSeconds;
    
    @Value("${spring.task.execution.thread-name-prefix:async-}")
    private String threadNamePrefix;

    /**
     * 异步任务执行线程池
     */
    @Bean(name = "taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setThreadNamePrefix(threadNamePrefix);
        
        // 线程池对拒绝任务(无线程可用)的处理策略
        // CallerRunsPolicy：由调用线程处理该任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        
        // 等待时间（默认为0，此时立即停止），并没等待xx秒后强制停止
        executor.setAwaitTerminationSeconds(60);
        
        // 线程名称前缀
        executor.setBeanName("taskExecutor");
        
        // 初始化
        executor.initialize();
        
        log.info("异步任务线程池配置完成 - 核心线程数: {}, 最大线程数: {}, 队列容量: {}", 
                corePoolSize, maxPoolSize, queueCapacity);
        
        return executor;
    }

    /**
     * 执行周期性或定时任务
     */
    @Bean(name = "scheduledExecutorService")
    protected ScheduledExecutorService scheduledExecutorService() {
        int poolSize = Runtime.getRuntime().availableProcessors();
        
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(
                poolSize,
                new BasicThreadFactory.Builder()
                        .namingPattern("schedule-pool-%d")
                        .daemon(true)
                        .build(),
                new ThreadPoolExecutor.CallerRunsPolicy()) {
            
            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                super.afterExecute(r, t);
                Threads.printException(r, t);
            }
        };
        
        log.info("定时任务线程池配置完成 - 线程数: {}", poolSize);
        return executor;
    }
}
